use crate::app::{App, AppMode, Message, NotificationType, TaskStatus};
use crate::logging::LogEntry;
use iced::{
    widget::{button, column, container, row, text, text_input, scrollable, Space, Column},
    Element, Length, Background, Color, Border, Alignment,
};

pub fn view(app: &App) -> Element<Message> {
    let content = if app.settings_open {
        settings_view(app)
    } else if app.log_window_open {
        log_view(app)
    } else {
        main_view(app)
    };

    let mut layout = column![
        header_view(app),
        content,
        footer_view(app),
    ]
    .spacing(10)
    .padding(20);

    // 如果有通知，显示通知
    if let Some(notification) = &app.notification {
        layout = layout.push(notification_view(notification));
    }

    container(layout)
        .width(Length::Fill)
        .height(Length::Fill)
        .into()
}

fn header_view(app: &App) -> Element<Message> {
    let title = if let Some(title) = &app.title {
        format!("GUI 任务管理器 - {}", title)
    } else {
        "GUI 任务管理器".to_string()
    };

    container(
        text(title)
            .size(24)
    )
    .width(Length::Fill)
    .padding(10)
    .into()
}

fn main_view(app: &App) -> Element<Message> {
    let mut content = column![
        row![
            button("添加任务").on_press(Message::AddTask),
            Space::with_width(10),
            button("设置").on_press(Message::ToggleSettings),
            Space::with_width(10),
            button("日志").on_press(Message::ToggleLogWindow),
            Space::with_width(10),
            button("退出").on_press(Message::Exit),
        ]
        .spacing(10),
        Space::with_height(20),
    ];

    if app.items.is_empty() {
        content = content.push(
            container(
                text("没有任务。点击'添加任务'来创建新任务。")
                    .size(16)
            )
            .padding(20)
        );
    } else {
        let tasks_list = app.items.iter().enumerate().fold(
            Column::new().spacing(10),
            |column, (index, task)| {
                column.push(task_item_view(task, index, app.selected_index == Some(index)))
            }
        );

        content = content.push(
            scrollable(tasks_list)
                .height(Length::Fill)
        );
    }

    content.into()
}

fn task_item_view(task: &crate::app::TaskItem, index: usize, is_selected: bool) -> Element<Message> {
    let status_color = match task.status {
        TaskStatus::Pending => Color::from_rgb(1.0, 1.0, 0.0), // 黄色
        TaskStatus::Running => Color::from_rgb(0.0, 0.0, 1.0), // 蓝色
        TaskStatus::Finished => Color::from_rgb(0.0, 1.0, 0.0), // 绿色
        TaskStatus::Failed => Color::from_rgb(1.0, 0.0, 0.0), // 红色
        TaskStatus::Stopped => Color::from_rgb(0.5, 0.5, 0.5), // 灰色
    };

    let status_text = match task.status {
        TaskStatus::Pending => "待处理",
        TaskStatus::Running => "运行中",
        TaskStatus::Finished => "已完成",
        TaskStatus::Failed => "失败",
        TaskStatus::Stopped => "已停止",
    };

    let mut task_content = column![
        row![
            text(&task.name).size(16),
            Space::with_width(10),
            text(status_text)
                .style(move |_theme| {
                    text::Style {
                        color: Some(status_color),
                    }
                }),
            Space::with_width(10),
            button(if task.expanded { "[-]" } else { "[+]" })
                .on_press(Message::ToggleTaskExpanded(index)),
            Space::with_width(10),
            button("启动").on_press(Message::StartTask(task.id)),
            Space::with_width(5),
            button("停止").on_press(Message::StopTask(task.id)),
            Space::with_width(5),
            button("失败").on_press(Message::SetTaskFailed(task.id)),
        ]
        .spacing(5),
    ];

    // 如果任务正在运行且有当前操作，显示操作状态
    if task.status == TaskStatus::Running {
        if let Some(action) = &task.current_action {
            task_content = task_content.push(
                text(format!("当前操作: {}", action))
                    .size(14)
            );
        }
    }

    // 如果展开则显示设置
    if task.expanded {
        let mut settings_column = Column::new().spacing(5);
        for (key, value) in &task.settings {
            settings_column = settings_column.push(
                text(format!("  {}: {}", key, value))
                    .size(12)
            );
        }
        task_content = task_content.push(settings_column);
    }

    let task_container = container(task_content)
        .padding(10)
        .width(Length::Fill);

    if is_selected {
        task_container
            .style(|_theme| container::Style {
                background: Some(Background::Color(Color::from_rgb(0.2, 0.2, 0.8))),
                border: Border {
                    color: Color::from_rgb(0.5, 0.5, 1.0),
                    width: 2.0,
                    radius: 5.0.into(),
                },
                ..Default::default()
            })
            .into()
    } else {
        task_container
            .style(|_theme| container::Style {
                background: Some(Background::Color(Color::from_rgb(0.1, 0.1, 0.1))),
                border: Border {
                    color: Color::from_rgb(0.3, 0.3, 0.3),
                    width: 1.0,
                    radius: 5.0.into(),
                },
                ..Default::default()
            })
            .into()
    }
}

fn settings_view(app: &App) -> Element<Message> {
    let mut content = column![
        row![
            button("返回").on_press(Message::ToggleSettings),
        ],
        Space::with_height(20),
        text("全局设置").size(20),
        Space::with_height(10),
    ];

    // 显示机器码
    content = content.push(
        text(format!("机器码: {}",
            app.machine_code.as_deref().unwrap_or("未生成")))
            .size(14)
    );

    content = content.push(Space::with_height(10));

    // 注册码设置
    content = content.push(
        row![
            text("注册码: ").size(14),
            if app.settings_editing.as_deref() == Some("注册码") {
                text_input("请输入注册码", &app.settings_input)
                    .on_input(Message::UpdateSettingInput)
                    .on_submit(Message::SaveSetting("注册码".to_string()))
            } else {
                text_input("", &app.reg_code_input)
                    .on_input(Message::UpdateRegCode)
            },
            Space::with_width(10),
            if app.settings_editing.as_deref() == Some("注册码") {
                button("保存").on_press(Message::SaveSetting("注册码".to_string()))
            } else {
                button("编辑").on_press(Message::EditSetting("注册码".to_string()))
            },
        ]
        .spacing(10)
    );

    content = content.push(Space::with_height(10));

    // 其他设置
    for (key, value) in &app.global_settings {
        content = content.push(
            row![
                text(format!("{}: ", key)).size(14),
                if app.settings_editing.as_ref() == Some(key) {
                    text_input("", &app.settings_input)
                        .on_input(Message::UpdateSettingInput)
                        .on_submit(Message::SaveSetting(key.clone()))
                } else {
                    text_input("", value)
                        .on_input(|_| Message::UpdateSettingInput(String::new()))
                },
                Space::with_width(10),
                if app.settings_editing.as_ref() == Some(key) {
                    button("保存").on_press(Message::SaveSetting(key.clone()))
                } else {
                    button("编辑").on_press(Message::EditSetting(key.clone()))
                },
            ]
            .spacing(10)
        );
    }

    scrollable(content).into()
}

fn notification_view(notification: &crate::app::Notification) -> Element<Message> {
    let color = match notification.notification_type {
        NotificationType::Info => Color::from_rgb(0.0, 1.0, 0.0),
        NotificationType::Warning => Color::from_rgb(1.0, 1.0, 0.0),
        NotificationType::Error => Color::from_rgb(1.0, 0.0, 0.0),
    };

    container(
        text(&notification.message)
            .style(move |_theme| {
                text::Style {
                    color: Some(color),
                }
            })
            .size(16)
    )
    .padding(10)
    .style(move |_theme| container::Style {
        background: Some(Background::Color(Color::from_rgb(0.1, 0.1, 0.1))),
        border: Border {
            color,
            width: 2.0,
            radius: 5.0.into(),
        },
        ..Default::default()
    })
    .into()
}

fn footer_view(app: &App) -> Element<Message> {
    let help_text = match app.mode {
        AppMode::Normal => "GUI 任务管理器 - 点击按钮进行操作",
        AppMode::Settings => "设置模式 - 配置应用程序设置",
    };

    container(
        text(help_text).size(12)
    )
    .padding(10)
    .into()
}

fn log_view(app: &App) -> Element<Message> {
    let mut content = column![
        // 日志窗口标题栏
        row![
            button("返回").on_press(Message::ToggleLogWindow),
            Space::with_width(10),
            button("清空日志").on_press(Message::ClearLogs),
            Space::with_width(10),
            button(if app.log_detailed { "简化模式" } else { "详细模式" })
                .on_press(Message::ToggleLogDetailed),
            Space::with_width(10),
            text(format!("日志总数: {}", app.logs.len())).size(14),
        ]
        .spacing(5)
        .align_y(Alignment::Center),
        Space::with_height(10),
    ];

    // 日志列表
    if app.logs.is_empty() {
        content = content.push(
            container(
                text("暂无日志记录")
                    .size(16)
            )
            .padding(20)
            .width(Length::Fill)
            .center_x(Length::Fill)
        );
    } else {
        // 滚动控制
        content = content.push(
            row![
                button("向上滚动").on_press(Message::ScrollLogsUp),
                Space::with_width(10),
                button("向下滚动").on_press(Message::ScrollLogsDown),
                Space::with_width(10),
                text(format!("位置: {}/{}",
                    app.log_scroll.saturating_add(1),
                    app.logs.len()
                )).size(14),
            ]
            .spacing(5)
            .align_y(Alignment::Center)
        );

        content = content.push(Space::with_height(10));

        // 显示可见的日志
        let visible_logs = app.get_visible_logs();
        let logs_column = visible_logs.iter().enumerate().fold(
            Column::new().spacing(5),
            |column, (_, log_entry)| {
                column.push(log_entry_view(log_entry, app.log_detailed))
            }
        );

        content = content.push(
            container(
                scrollable(logs_column)
                    .height(Length::FillPortion(8))
            )
            .padding(10)
            .style(|_theme| container::Style {
                background: Some(Background::Color(Color::from_rgb(0.05, 0.05, 0.05))),
                border: Border {
                    color: Color::from_rgb(0.3, 0.3, 0.3),
                    width: 1.0,
                    radius: 5.0.into(),
                },
                ..Default::default()
            })
        );

        // 日志导航信息
        content = content.push(
            container(
                text(format!(
                    "显示 {}/{} 条日志 | 使用滚动按钮查看更多",
                    visible_logs.len(),
                    app.logs.len()
                ))
                .size(12)
            )
            .padding(5)
            .center_x(Length::Fill)
        );
    }

    content.into()
}

fn log_entry_view(log_entry: &LogEntry, detailed: bool) -> Element<Message> {
    let level_color = match log_entry.level.as_str() {
        "ERROR" => Color::from_rgb(1.0, 0.3, 0.3),
        "WARN" => Color::from_rgb(1.0, 0.8, 0.0),
        "INFO" => Color::from_rgb(0.3, 0.8, 1.0),
        "DEBUG" => Color::from_rgb(0.7, 0.7, 0.7),
        "TRACE" => Color::from_rgb(0.5, 0.5, 0.5),
        _ => Color::from_rgb(1.0, 1.0, 1.0),
    };

    let formatted_text = if detailed {
        log_entry.format_detailed()
    } else {
        log_entry.format_simple()
    };

    let log_text = text(formatted_text)
        .size(12)
        .style(move |_theme| {
            text::Style {
                color: Some(level_color),
            }
        });

    container(log_text)
        .padding(5)
        .width(Length::Fill)
        .style(|_theme| container::Style {
            background: Some(Background::Color(Color::from_rgb(0.02, 0.02, 0.02))),
            border: Border {
                color: Color::from_rgb(0.2, 0.2, 0.2),
                width: 0.5,
                radius: 3.0.into(),
            },
            ..Default::default()
        })
        .into()
}
